<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .item {
            width: 100px;
            height: 100px;
            background: lightgreen;
            margin: 10px;
        }
    </style>
</head>

<body>
    <div class="item">div1</div>
    <div class="item">div2</div>
    <div class="item">div3</div>

    <script>
        var items = document.querySelectorAll(".item");
        for (var i = 0; i < items.length; i++) {
            items[i].onclick = function (n) {
                return function () {
                    alert(n);
                }
            }(i);
        };
    </script>
</body>

</html>